package com.ocom.oauth.config;

import com.alibaba.fastjson.JSON;
import com.ocom.common.utils.ResultUtil;
import com.ocom.oauth.po.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        //此处返回true,表示对任何handler的responsebody都调用beforeBodyWrite方法，如果有特殊方法不使用可以考虑使用注解等方式过滤
        return true;
    }

    /**
     * 对Controller的所有返回结果进行处理
     * @param body 是controller方法中返回的值，对其进行修改后再return
     * @param methodParameter
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        assert (body != null ? body.getClass().getName() : null) !=null;
        log.info("请求返回数据类型class="+ body.getClass().getName());
        log.info("body="+ body.toString());
        serverHttpResponse.setStatusCode(HttpStatus.OK);
        if(body.getClass().getName().equals("java.lang.String") || body.getClass().getName().equals("com.ocom.common.resp.Result") ){
            return body;
        }
        if (body.toString().contains("error") && body.toString().contains("Unauthorized") || body.toString().contains("error")){
            return ResultUtil.info(10002,body.toString().substring(41).replace("\"",""));
        }else if (body.toString().contains("error")){
            return new JsonResult<Object>(10001,body);
        }
        if (log.isDebugEnabled()) {
            log.debug("请求返回数据body=     " + body.toString());
        }

        if(body.getClass().getName().equals("org.springframework.security.oauth2.common.DefaultOAuth2AccessToken")){
            String jsonMap= JwtHelper.decode(body.toString()).getClaims();
            Map<String,Object> objectMap= JSON.parseObject(jsonMap, HashMap.class);;
            String clientId=String.valueOf(objectMap.get("client_id"));
            //微信返回格式處理
            if(clientId.equals("client_2")){
                Map<String,Object> returnMap = new HashMap<>();
                returnMap.put("openid",objectMap.get("user_name"));
                returnMap.put("skey",body.toString());
                returnMap.put("companyId",objectMap.get("comId"));
                returnMap.put("nextPage",2);
                returnMap.put("exp",objectMap.get("exp"));
                return ResultUtil.success(returnMap);
            }
            //用户小程序返回格式處理
            if(clientId.equals("client_3")){
                Map<String,Object> returnMap = new HashMap<>();
                returnMap.put("openid",objectMap.get("user_name"));
                returnMap.put("skey",body.toString());
                returnMap.put("companyId",objectMap.get("comId"));
                returnMap.put("nextPage",2);
                returnMap.put("exp",objectMap.get("exp"));
                return ResultUtil.success(returnMap);
            }
        }
        return ResultUtil.success(body);
    }
}
